<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Single extends CI_Controller
{
    const FLAG_EXIT = 'exit';
    const FLAG_RUNNING = 'running';

    protected $flag = self::FLAG_RUNNING;

    /**    
     *
     * @var \Rabbitmq 
     */
    public $rabbitmq;

    public function __construct()
    {
        parent::__construct();
        $this->load->library('Rabbitmq', ['conf' => 'amazon']);
        pcntl_async_signals(true);
    }

    protected function set_system_signal_handler()
    {
        //平滑退出
        pcntl_signal(SIGTERM, function () {
            $this->flag = self::FLAG_EXIT;
        });
    }

    public function push_mq($log_level, $msg)
    {
        $exchange_name = 'klc-22';
        $queue = "klc-22";
        // $this->rabbitmq->set_is_delay_message(true);

        $i = 0;

        $this->rabbitmq->dirct_push($exchange_name, $queue, $log_level, $msg . (++$i), 20);
        $this->rabbitmq->dirct_push($exchange_name, $queue, $log_level, $msg . (++$i), 19);
        $this->rabbitmq->dirct_push($exchange_name, $queue, $log_level, $msg . (++$i), 2);
        $this->rabbitmq->dirct_push($exchange_name, $queue, $log_level, $msg . (++$i), 30);
        $this->rabbitmq->dirct_push($exchange_name, $queue, $log_level, $msg . (++$i), 8);

        // for($i=0;$i<100;$i++){           
        //     $this->rabbitmq->dirct_push($log_level,$msg.time().'--'.rand(0,10000).'--'.$i);            
        // }

    }

    public function pop_mq()
    {
        $k = [];

        // $queue_name = 'abc';
        // $exchange_name = 'ex_log';
        // $routing_key = 'info';

        $queue_name = 'klc-22';
        $exchange_name = 'klc-22';
        $routing_key = 'info';

        // $this->rabbitmq->set_is_delay_message(true);
        $this->rabbitmq->consume($queue_name, $exchange_name, $routing_key, function (\AMQPEnvelope $env, \AMQPQueue $que) use ($k) {
            $msg = sprintf("from %s exchange,%s routing key,body is :%s", $env->getExchangeName(), $env->getRoutingKey(), $env->getBody());
            writeln($msg);
            $k[$env->getDeliveryTag()] = isset($k[$env->getDeliveryTag()]) ? $k[$env->getDeliveryTag()] + 1 : 1;

            // $que->ack($env->getDeliveryTag());
            $que->nack($env->getDeliveryTag());
            // writeln($k[$env->getDeliveryTag()]);
        });
    }

    public function index()
    {
        $queue_name = 'klc-22';
        $exchange_name = 'klc-22';
        $routing_key = 'info';

        $this->rabbitmq->mq_get($queue_name, $exchange_name, $routing_key);
    }
}
